package com.java.module.system.service.impl;

import java.util.List;
import java.util.Objects;

import com.java.common.constant.Constants;
import com.java.common.lang.enums.UserTypeEnum;
import com.java.common.service.ApiTokenService;
import com.java.common.service.TokenService;
import com.java.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.java.module.system.domain.SysLogininfor;
import com.java.module.system.mapper.SysLogininforMapper;
import com.java.module.system.service.ISysLogininforService;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author Administrator
 */
@Service
public class SysLogininforServiceImpl implements ISysLogininforService {

    @Autowired
    private SysLogininforMapper logininforMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ApiTokenService apiTokenService;

    @Value(value = "${user.username.single}")
    private boolean single;

    /**
     * 新增系统登录日志
     *
     * @param logininfor 访问日志对象
     * @param status LOGIN_SUCCESS
     */
    @Override
    public void insertLogininfor(SysLogininfor logininfor, String status) {
        if (single && Objects.equals(status, Constants.LOGIN_SUCCESS)) {
            forceLogout(logininfor.getUserName(), logininfor.getUserType());
        }
        logininforMapper.insertLogininfor(logininfor);
    }

    /**
     * 查询系统登录日志集合
     *
     * @param logininfor 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLogininfor> selectLogininforList(SysLogininfor logininfor) {
        return logininforMapper.selectLogininforList(logininfor);
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return
     */
    @Override
    public int deleteLogininforByIds(Long[] infoIds) {
        return logininforMapper.deleteLogininforByIds(infoIds);
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor() {
        logininforMapper.cleanLogininfor();
    }

    /**
     * 强退最后登录
     */
    private void forceLogout(String userName, int userType) {
        SysLogininfor logininfor = logininforMapper.selectLastLogininfor(userName, userType);
        if (logininfor == null) {
            return;
        }
        String token = logininfor.getToken();
        if (StringUtils.isEmpty(token)) {
            return;
        }
        if (userType == UserTypeEnum.ADMIN.getType()) {
            tokenService.delLoginUser(token);
            return;
        }
        if (userType == UserTypeEnum.USER.getType()) {
            apiTokenService.delLoginUser(token);
        }
    }

}